<template>
  <div class="procure-outbound-add">
    <div class="info">
      <div>
        <div class="left">
          <p class="creater mr40">制单人：{{ userInfo.createBy || "-" }}</p>
          <p class="mr40">制单时间：{{ userInfo.createTime || "-" }}</p>
          <p>出库编码：{{ userInfo.deliveryNo || "-" }}</p>
        </div>
        <div class="right">
          <el-button type="info" plain @click="$router.push({ path: '/procure/outbound', query: {} })">返回</el-button>
        </div>
      </div>
    </div>

    <el-container class="content">
      <el-aside>
        <header>
          <div class="supper">
            <p>出库仓</p>
            <el-select
              v-model="houseValue"
              placeholder="请选择"
              clearable
              @change="
                val => {
                  changeHouse(val);
                }
              "
            >
              <el-option
                v-for="item in storeList"
                :key="item.warehouseId"
                :label="item.warehouseName"
                :value="item.warehouseId"
              />
            </el-select>
          </div>
          <el-button :disabled="!houseValue" type="primary" @click="toPath"> 添加商品 </el-button>
        </header>

        <!-- 商品列表 -->
        <div class="products-list" style="overflow-x: auto">
          <div class="my-table" style="min-width: 1300px">
            <div class="table-header">
              <div>
                <div>
                  <div class="col1">商品信息</div>
                  <div class="col2">数量</div>
                  <div class="col3">预计出库件数</div>
                  <div class="col4">单位</div>
                  <div class="col5">实际出库数量</div>
                  <div class="col6">实际出库件数</div>
                  <div class="col7">仓库</div>
                  <div class="col8">操作</div>
                </div>
              </div>
            </div>

            <div class="table-body" v-if="list.length > 0">
              <div class="list-item" v-for="(item, index) in list" :key="index">
                <div>
                  <div class="col1">
                    <div>
                      <div class="left">
                        <img :src="item.mainPicUrl" alt="" />
                      </div>
                      <div class="right">
                        <h3 class="name text-break">{{ item.productAliasName || "-" }}</h3>
                        <p style="white-space: break-spaces">
                          <!-- {{ getSpes(item.properties) }} -->
                          {{ item.skuSpecification }}
                        </p>
                        <p>SKU编码：{{ item.skuCode || "-" }}</p>
                        <p>ID:{{ item.productId || "-" }}</p>
                      </div>
                    </div>
                  </div>
                  <div class="col2">
                    {{ item.availuableNum || "-" }}
                  </div>
                  <div class="col3">
                    {{ item.availuablePartNum || "-" }}
                  </div>
                  <div class="col4">
                    {{ getName(item.productUnit) || "-" }}
                  </div>
                  <div class="col5">
                    <el-input-number
                      :min="1"
                      :max="item.availuableNum || 1"
                      :precision="0"
                      controls-position="right"
                      style="width: 100px"
                      v-model="item.deliveryQuantity"
                      @change="
                        () => {
                          // item.deliveryPartQuantity =
                          //   (Number(item.availuablePartNum) / Number(item.availuableNum)) * Number(item.deliveryQuantity) || 0;
                        }
                      "
                      @keydown="channelInputLimit"
                    ></el-input-number>
                  </div>
                  <div class="col6">
                    <!-- {{ (Number(item.availuablePartNum) / Number(item.availuableNum)) * Number(item.deliveryQuantity) || 0 }} -->
                    <el-input-number
                      :min="0"
                      :max="item.availuablePartNum || 0"
                      :precision="0"
                      controls-position="right"
                      style="width: 100px"
                      v-model="item.deliveryPartQuantity"
                      @keydown="channelInputLimit"
                    ></el-input-number>
                  </div>
                  <div class="col7">{{ item.warehouseName || "-" }}</div>
                  <div class="col8">
                    <el-button @click="clickDel(item)" size="small" link type="primary">移除</el-button>
                  </div>
                </div>
                <div class="tips">
                  <p class="label">备注</p>
                  <!-- <el-input maxlength="200" v-model="item.remark" placeholder="请输入"></el-input> -->
                  <RemarkEditor v-model="item.remark" />
                </div>
              </div>
            </div>
            <div v-else style="display: flex; justify-content: center; width: 100%">
              <el-empty description="暂无数据" />
            </div>
          </div>
        </div>
      </el-aside>
      <el-main width="300px">
        <div class="ck-time mb20">
          <p>期望出库日期</p>
          <el-date-picker
            v-model="ckTime"
            value-format="YYYY-MM-DD  HH:mm:ss"
            type="datetime"
            placeholder="请选择"
            style="width: 100%"
          />
        </div>

        <div class="divider"></div>

        <!-- 关联借调客户信息 -->
        <SecondCustomer
          ref="secondCustomerRef"
          title="关联客户信息"
          remarkTitle="关联备注说明"
          dialogTitle="添加关联客户"
          actionTips="确定要取消关联客户信息？"
        />
        <div class="divider"></div>

        <!-- 入库备注 -->
        <div class="ck-tips">
          <p class="label">出库备注</p>
          <!-- <el-input maxlength="200" v-model="textarea" :rows="10" type="textarea" placeholder="请输入" /> -->
          <RemarkEditor v-model="textarea" />
        </div>
      </el-main>
    </el-container>

    <!-- 操作按钮栏 -->
    <div class="action-wrap">
      <!-- <el-button type="info" plain>取消</el-button> -->
      <el-button type="primary" :disabled="list.length <= 0" @click="submit">创建出库单</el-button>
    </div>

    <!-- 确认暂存的list会清空 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenClear"
      :message="'您正在重新选择出库仓，当前商品信息将被重置，重新添加商品，请问是否继续当前操作？'"
      :submitBtnText="'继续'"
      @submit="returnSubmitClear"
      @cancel="returnCancelClear"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import SearchForm from "@/components/SearchForm";
import { Search, RefreshRight, CloseBold } from "@element-plus/icons-vue";
import { getSuppliers } from "@/apis/products/specifications";
import moment from "moment";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import { getTempProductSkuList, newInboundOrder, delTempProductSku } from "@/apis/procure/entry";
import { ListPage } from "@/apis/procure/warehouse";
import { ElMessage, ElMessageBox } from "element-plus";
import useCodeArrStore from "@/store/modules/select";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import china from "@/utils/china.json";
import {
  createOtherDeliveryOrderInfo,
  getTempProductSkuListDelivery,
  delTempProductSkuDelivery,
  crateOtherDeliveryOrder,
  getCustomList
} from "@/apis/procure/outbound";
import { _throttle, channelInputLimit } from "@/utils";
import RemarkEditor from "@/components/RemarkEditor";
import SecondCustomer from "./components/secondCustomer.vue";

const secondCustomerRef = ref();
const storeList = ref([]); //收货仓库下拉数据
const houseValue = ref(""); //选中的出库仓
const list = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const ckTime = ref("");
const textarea = ref("");
const userInfo = ref({});
const _isOpenClear = ref(false);
const psList = ref([{ label: "配送人A", value: 1 }]); //配送人员下拉数据
const psValue = ref(null); //选中的配送人员
const form = ref({}); //收货信息表单数据
const formRef = ref();
const form2 = ref({}); //新建配送人表单数据
const form2Ref = ref();
const mapList = ref(china);
const dialogVisible = ref(false);

onMounted(async () => {
  const info = await createOtherDeliveryOrderInfo();
  userInfo.value = info.data;

  const res2 = await ListPage({ page: 1, size: 9999 }); //出库仓
  storeList.value = res2.data.records;
  // const res = await getSuppliers();
  // houseList.value = res.data;
  // userInfo.value = {
  //   name: JSON.parse(localStorage.getItem("userinfo")).tenantName,
  //   time: moment().format("YYYY/MM/DD HH:mm:ss")
  // };

  if (route.query.warehouseId) houseValue.value = route.query.warehouseId;

  getList();
});

//打开新建配送人弹窗
const openAdd = () => {
  dialogVisible.value = true;
};
//关闭新建配送人弹窗
const closeAdd = () => {
  form2Ref.value.resetFields();
  dialogVisible.value = false;
};

//确认新建配送人
const addSubmit = () => {
  form2Ref.value.validate((valid, fields) => {
    if (valid) {
      closeAdd();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const cascaderRef = ref();
const handleChange = value => {
  console.log("producerList", value);
  const nodes = cascaderRef.value.getCheckedNodes();
  console.log("找到了当前选中的节点数据===", nodes);
  form.value.provinceId = nodes[0].pathValues[0];
  form.value.cityId = nodes[0].pathValues[1];
  form.value.districtId = nodes[0].pathValues[2];
  form.value.provinceName = nodes[0].pathLabels[0];
  form.value.cityName = nodes[0].pathLabels[1];
  form.value.districtName = nodes[0].pathLabels[2];
};

const changeHouse = val => {
  if (route.query.warehouseId && route.query._time && list.value.length > 0) {
    _isOpenClear.value = true;
  } else {
    returnSubmitClear();
  }
};

const toPath = () => {
  if (route.query._time && houseValue.value === route.query.warehouseId) {
    router.push({
      path: "/procure/outbound/select-prod",
      query: { warehouseId: houseValue.value, _time: route.query._time }
    });
  } else {
    router.push({
      path: "/procure/outbound/select-prod",
      query: { warehouseId: houseValue.value, _time: new Date().getTime() }
    });
  }
};
const returnSubmitClear = () => {
  _isOpenClear.value = false;
  router.push({
    path: "/procure/outbound/add",
    query: { warehouseId: houseValue.value, _time: new Date().getTime() }
  });
  setTimeout(() => {
    list.value = [];
  }, 300);
};
const returnCancelClear = () => {
  houseValue.value = route.query.warehouseId;
};

const clickDel = row => {
  delTempProductSkuDelivery({
    code: route.query._time,
    skuId: row.businessSkuId
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "移除成功！",
        type: "success"
      });
      getList();
    }
  });
  // console.log("删除暂存数据", row);
};

const getName = code => {
  return useCodeArrStore().getDictName("shop_unit", code);
};

//确认创建出库单
const submit = _throttle(() => {
  const isEmpty = list.value.some(item => {
    if (item.deliveryQuantity <= 0 || !item.deliveryQuantity) {
      ElMessage({
        message: "请完整填写“实际出库数量”",
        type: "error"
      });
      return true;
    }
  });
  if (!isEmpty) {
    // console.log("关联借调用户", secondCustomerRef.value.getData());
    // return;
    const jdInfo = secondCustomerRef.value.getData();
    crateOtherDeliveryOrder({
      warehouseId: route.query.warehouseId,
      deliveryNo: userInfo.value.deliveryNo,
      expectStockTime: ckTime.value,
      remark: textarea.value,
      childReqList: list.value,
      secondmentCustomerId: jdInfo?.customerId || "", //借调客户id
      secondmentCustomerName: jdInfo?.receivingName || "", //借调客户名称
      secondmentCustomerPhone: jdInfo?.receivingMobile || "", //借调客户号码
      secondmentCustomerAddress: jdInfo?.address || "", //借调客户地址
      secondmentCustomerRemark: jdInfo?.secondmentCustomerRemark || "" //借调客户备注
    }).then(res => {
      if (res.code === 200) {
        ElMessageBox.confirm("", "", {
          cancelButtonText: "取消",
          confirmButtonText: "前往查看",
          dangerouslyUseHTMLString: true,
          message: "<div class='img'></div><p>订单出库申请创建成功，可前往订单出库申请中查看！</p>",
          customClass: "my-success-messagebox",
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false
        })
          .then(() => {
            console.log("前往出库列表查看");
            router.push({ path: "/procure/outbound" });
          })
          .catch(async () => {
            // 取消

            const info = await createOtherDeliveryOrderInfo();
            userInfo.value = info.data;

            getList();
          });
      }
    });
  }
}, 1000);

//查询列表数据
const getList = () => {
  if (route.query._time) {
    getTempProductSkuListDelivery({
      code: route.query._time,
      warehouseId: route.query.warehouseId
      // businessId: JSON.parse(localStorage.getItem("userinfo")).tenantId
    }).then(res => {
      if (res.code === 200) {
        list.value = res.data;
        // list.value = [{}, {}, {}];
        for (let item of list.value) {
          // item.availuableNum = 2;
          // item.availuablePartNum = 6;
          item.deliveryQuantity = 1;
          item.deliveryPartQuantity = 0;
        }
      }
    });
  }
};
//拼接商品的sku规格
const getSpes = properties => {
  if (!properties) return "-";
  const arr = JSON.parse(properties) || [];
  if (arr.length > 1) {
    const str = arr.reduce((a, b) => {
      return a.specificationVal + "+" + b.specificationVal;
    });
    return str;
  } else if (arr.length === 1) {
    return arr[0].specificationVal;
  } else {
    return "-";
  }
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
.divider {
  border-bottom: 1px solid #e2e8f0;
  margin: 20px -20px;
}
.procure-outbound-add {
  height: calc(100% - 64px);
  overflow-y: auto;
  padding: 0 20px 64px 20px;
  position: relative;

  // .search-wrap {
  //   padding: 20px;
  //   overflow-x: hidden;
  //   background-color: #f6f8fa;
  // }

  .info {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 22;
    & > div {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 14px 0;
      border-bottom: 1px solid #e2e8f0;
    }
    & > div > div {
      display: flex;
    }
    .left {
      .creater {
        color: #1a1a1a;
        font-weight: bold;
      }
    }
  }
  .content {
    height: calc(100% - 62px);
    :deep(.el-aside) {
      flex: 1;
      padding: 20px 20px 20px 0;
      header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 18px;
        .supper {
          flex: 1;
          display: flex;
          align-items: center;
          padding-right: 20px;
          p {
            width: 52px;
          }
          .el-select {
            flex: 1;
          }
        }
      }
      .products-list {
        .table-header {
          background-color: #f2f6fc;
          margin-bottom: 10px;
        }
        .table-body {
          .list-item {
            margin-bottom: 10px;
            & > div {
              border: 1px solid #e1e6ed;
              display: flex;
              // align-items: center;
              &:not(:first-of-type) {
                border-left: none;
              }
              &:not(:last-of-type) {
                & > div:not(:last-of-type) {
                  border-right: 1px solid #e1e6ed;
                }
              }
              & > div {
                display: flex;
                align-items: center;
              }
            }
            .col1 {
              & > div {
                display: flex;
              }

              .left {
                img {
                  width: 80px;
                  height: 80px;
                  border-radius: 4px;
                }
              }
              .right {
                padding-left: 18px;
                .name {
                  font-size: 14px;
                  color: #3d3d3d;
                  margin-bottom: 5px;
                }
                p {
                  font-size: 12px;
                  color: #86909c;
                  margin-bottom: 5px;
                }
              }
            }
            .tips {
              display: flex;
              padding: 16px 14px;
              border-top: none;
              border-left: 1px solid #e1e6ed !important;
              p.label {
                width: 38px;
              }
              .el-input {
                flex: 1;
                .el-input__wrapper {
                  background-color: #f2f3f5;
                }
              }
            }
          }
        }
        .table-header,
        .table-body {
          & > div > div:first-of-type {
            display: flex;
            justify-content: space-between;
            & > div {
              padding: 14px 20px;
              &.col1 {
                // width: 45%;
                flex: 1;
                min-width: 400px;
              }
              &.col2,
              &.col4,
              &.col7,
              &.col8 {
                width: 80px;
                box-sizing: border-box;
              }
              &.col3 {
                width: 140px;
                box-sizing: border-box;
              }
              &.col5,
              &.col6 {
                width: 125px;
                box-sizing: border-box;
              }
            }
          }
        }
      }
    }
    :deep(.el-main) {
      width: 300px;
      flex: none;
      background-color: #f6f8fa;
      border-left: 1px solid #e2e8f0;
      .ck-time,
      .ps-people {
        p {
          width: 120px;
          margin-bottom: 10px;
        }
        .el-select {
          flex: 1;
        }
      }
      .ps-people {
        & > div {
          display: flex;
          .el-button {
            font-size: 12px;
          }
        }
      }
      .kh-info {
        h3 {
          color: #86909c;
          font-weight: normal;
          margin: 20px 0 16px 0;
        }
        p {
          color: #86909c;
          margin-bottom: 10px;
        }
        b {
          font-weight: normal;
          color: #1a1a1a;
        }
      }
      .sh-info {
        & > p {
          font-size: 16px;
          color: #86909c;
          margin-bottom: 10px;
        }
        .el-form-item {
          flex-direction: column;
        }
        .el-form-item__label-wrap {
          margin-left: 0 !important;
        }
      }
      .ck-tips {
        p.label {
          color: #4e5969;
          margin-bottom: 16px;
        }
      }
    }
  }
  .action-wrap {
    position: absolute;
    bottom: 0;
    right: 0;
    left: 0;
    height: 64px;
    background-color: white;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20px;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
  }
}
</style>
